import * as elIcons from '@element-plus/icons-vue'
import type {App} from 'vue'
import {XYtoXYZ, XYZtoSRGB, SRGBtoRGB} from './function.js'
import {isArray, pickBy, cloneDeep} from "lodash";
import path from "path";
import fs from "fs";
import axios from "axios";
import {useApiStore} from "@/stores/modules/apiStore/apiStore";
import {pinia} from "@/stores";


export function getUUIDForFDFB() {


    var s: any = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

export function getColorId() {
    var s: any = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    // s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}


/*
* 全局注册element Plus的icon
*/
export function registerIcons(app: App) {
    const icons = elIcons as any
    for (const i in icons) {
        app.component(`el-icon-${icons[i].name}`, icons[i])
    }
}


/**
 * 是否是外部链接
 * @param path
 */
export function isExternal(path: string): boolean {
    return /^(https?|ftp|mailto|tel):/.test(path)
}

/**
 * 加载网络css文件
 * @param url css资源url
 */
export function loadCss(url: string): void {
    const link = document.createElement('link')
    link.rel = 'stylesheet'
    link.href = url
    link.crossOrigin = 'anonymous'
    document.getElementsByTagName('head')[0].appendChild(link)
}

/**
 * 加载网络js文件
 * @param url js资源url
 */
export function loadJs(url: string): void {
    const link = document.createElement('script')
    link.src = url
    document.body.appendChild(link)
}

// @ts-ignore
export function transformTozTreeFormat(sNodes) { //将普通的数组转换为父子结构
    var i, l;
    // @ts-ignore
    var r = [];
    var tmpMap = {};
    for (i = 0, l = sNodes.length; i < l; i++) {
        // @ts-ignore
        tmpMap[sNodes[i].id] = sNodes[i];
    }
    for (i = 0, l = sNodes.length; i < l; i++) {
        // @ts-ignore
        var p = tmpMap[sNodes[i].parentId];
        // @ts-ignore
        if (p && sNodes[i].id != sNodes[i].parentId) {
            // @ts-ignore
            var children = this.nodeChildren(p);
            if (!children) {
                // @ts-ignore
                children = this.nodeChildren(p, []);
            }
            children.push(sNodes[i]);
        } else {
            r.push(sNodes[i]);
        }
    }
    // @ts-ignore
    return r;
}


/**
 * 获取图片地址(全路径)
 * @param path
 */
export function getImage(path: string) {
    if (!path) {
        return ''
    } else {
        return window.apiObj.APP_API_ORIGIN + window.apiObj.APP_API_PREFIX + '/file/show?fileCatalog=' + path
    }

}

/**
 * 获取首页分享地址(全路径)
 * @param path
 */
export function gethomeShare(path: string, id: string) {
    if (!path || !id) {
        return ''
    } else {
        return window.apiObj.APP_API_ORIGIN + window.apiObj.APP_BASE + '/#/home/share?selectId=' + path + '&shareId=' + id
    }

}

/**
 * 将CIE坐标转化为颜色
 * @param event
 */
export function XYtoRGB(event1: any) {
    console.log(event1)
    const event = event1
    if (!event1) return
    let x = event.x;
    let y = event.y;
    if (isArray(event)) {
        x = event[0]
        y = event[1]
    } else if (!event.x || !event.y) return

    console.log(x, y)
    let color: any = XYtoXYZ(x, y);
    color = XYZtoSRGB(color);
    color = SRGBtoRGB(color);
    const currentColor = `rgb(${parseFloat(color.r * 255.0).toFixed(0)} ${parseFloat(color.g * 255.0).toFixed(0)} ${parseFloat(color.b * 255.0).toFixed(0)})`
    console.log(currentColor)
    return currentColor
}

/*
*判断一个多层对象中是否有空值
* */
export function hasEmptyValue(obj: any) {
    for (let prop in obj) {
        if (prop == 'item' && !obj[prop]?.length) {
            return true;
        }
        if (obj.hasOwnProperty(prop)) {
            if (obj[prop] === null || obj[prop] === undefined || obj[prop] === '') {
                console.log(obj[prop])
                console.log(obj)
                return true;
            }
            if (typeof obj[prop] === 'object') {
                if (hasEmptyValue(obj[prop])) {
                    return true;
                }
            }
        }
    }
    return false;
}


/*
*连线校验
* */
export function hasEmptyLineValue(obj: any) {
    let initObj = cloneDeep(obj)
    let mark = false
    if (initObj?.andor) {
        if (!initObj.item?.length) return true
        initObj = pickBy(initObj)
    } else {
        delete initObj?.andor;
        if (!initObj?.item) {
            delete initObj?.item;
        }
    }
    for (let prop in initObj) {
        if (initObj.hasOwnProperty(prop)) {
            if (initObj[prop] === null || initObj[prop] === undefined || initObj[prop] === '') {
                return true;
            }
            if (initObj[prop] instanceof Array) {
                for (let i = 0; i < initObj[prop]?.length; i++) {
                    if (hasEmptyLineValue(initObj[prop][i])) {
                        mark = true;
                        break
                    }
                }

            }
        }
    }
    return mark;
}


export const configData = () => {
    const apiStore = useApiStore();
    let params: any = {
        // APP_API_ORIGIN: import.meta.env.APP_API_ORIGIN,
        // APP_API_PREFIX: import.meta.env.APP_API_PREFIX,
        APP_BASE: window.apiObj.APP_BASE,
        // APP_MQTT_HOST: import.meta.env.APP_MQTT_HOST,
        // APP_MQTT_PORT: import.meta.env.APP_MQTT_PORT,
        // APP_MQTT_ENDPOINT: import.meta.env.APP_MQTT_ENDPOINT,
    }
    // console.log(apiStore.staticConfig)
    // console.log(apiStore.staticConfig?.isFinish)
    // if (!apiStore.staticConfig?.isFinish) {
    //     const init: any = getStatic()
    //     console.log(init)
    //     params = {
    //         ...params,
    //         ...init
    //     }
    // } else {
    //     params = {
    //         ...params,
    //         ...apiStore.staticConfig
    //     }
    // }
    console.log(params)
    return params

}


export const getStatic = () => {
    const apiStore = useApiStore();
    // 获取public下 data 文件夹中的test.json文件数据

    // 局部使用
    const service = axios.create({
        baseURL: '', // 请求本地json文件，那么baseURL取空字符串，域名就会是项目域名
        timeout: 30000,
    });
    return new Promise((resolve, reject) => {
        return service.get('config' + '.json').then((res: any) => {
            console.log(res)
            apiStore.staticConfig = {
                ...res.data,
                isFinish: true
            }
            console.log(apiStore.staticConfig)
            resolve(res.data)
        })
    })

}
